import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Select, 
  Button, 
  Row, 
  Col, 
  Space, 
  message,
  Upload,
  InputNumber,
  Divider,
  Table,
  Popconfirm,
  Tag
} from 'antd';
import { 
  PlusOutlined, 
  UploadOutlined 
} from '@ant-design/icons';
import { createProduct, updateProduct, getOssSign } from '../../api/shop';
import type { UploadFile } from 'antd/es/upload/interface';

const { Option } = Select;
const { TextArea } = Input;

interface CommodityEditFormProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  productData?: any; // 编辑时的商品数据
  isEdit?: boolean;
  productId?: number; // 编辑时的商品ID
}

const CommodityEditForm: React.FC<CommodityEditFormProps> = ({
  visible,
  onCancel,
  onSuccess,
  productData,
  isEdit = false,
  productId
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [attachments, setAttachments] = useState<Array<{type: string, url: string}>>([]);
  const [tags, setTags] = useState<string[]>([]);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');

  // 初始化表单数据
  useEffect(() => {
    if (visible) {
      if (isEdit && productData) {
        // 编辑模式：填充现有数据
        form.setFieldsValue({
          ...productData,
          product_price: productData.product_price / 100, // 分转元
          cost_price: productData.cost_price / 100,
          sales_price: productData.sales_price / 100,
          support_life_points: productData.support_life_points,
          proxy_commission_ratio: productData.proxy_commission_ratio * 100, // 小数转百分比
          skus: productData.skus || []
        });
        
        // 处理图片数据 - 解析attachments数组
        if (productData.attachments) {
          try {
            console.log('原始附件数据:', productData.attachments);
            const attachmentsArray = JSON.parse(productData.attachments);
            console.log('解析后的附件数据:', attachmentsArray);
            
            // 设置attachments数组
            setAttachments(attachmentsArray);
            
            // 同时设置fileList用于显示
            const files = attachmentsArray.map((att: any, index: number) => {
              console.log(`处理附件 ${index}:`, att);
              return {
                uid: `existing-${index}-${Date.now()}`,
                name: `image-${index + 1}`,
                status: 'done' as const,
                url: att.url,
                thumbUrl: att.url,
                response: { url: att.url }
              };
            });
            
            console.log('处理后的文件列表:', files);
            setFileList(files);
          } catch (error) {
            console.error('解析附件数据失败:', error);
            // 如果解析失败，尝试直接使用字符串URL
            if (typeof productData.attachments === 'string' && productData.attachments.startsWith('http')) {
              const attachmentsArray = [{ type: 'image', url: productData.attachments }];
              setAttachments(attachmentsArray);
              
              const files = [{
                uid: `existing-0-${Date.now()}`,
                name: 'image-1',
                status: 'done' as const,
                url: productData.attachments,
                thumbUrl: productData.attachments,
                response: { url: productData.attachments }
              }];
              console.log('使用字符串URL创建文件列表:', files);
              setFileList(files);
            }
          }
        } else {
          setAttachments([]);
        }
        
        // 处理标签数据
        if (productData.product_tags) {
          try {
            const tagsArray = JSON.parse(productData.product_tags);
            setTags(Array.isArray(tagsArray) ? tagsArray : []);
          } catch (error) {
            // 如果不是JSON，尝试按逗号分割
            const tagsArray = productData.product_tags.split(',').map((tag: string) => tag.trim()).filter((tag: string) => tag);
            setTags(tagsArray);
          }
        } else {
          setTags([]);
        }
      } else {
        // 创建模式：重置表单
        form.resetFields();
        setFileList([]);
        setAttachments([]);
        setTags([]);
        form.setFieldsValue({
          category_id: 1,
          sales_type: 1,
          support_life_points: 1,
          proxy_commission_ratio: 10, // 10% 显示
          skus: []
        });
      }
    }
  }, [visible, isEdit, productData, form]);

  // 标签管理函数
  const handleClose = (removedTag: string) => {
    const newTags = tags.filter(tag => tag !== removedTag);
    setTags(newTags);
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue && tags.indexOf(inputValue) === -1) {
      setTags([...tags, inputValue]);
    }
    setInputVisible(false);
    setInputValue('');
  };

  // 处理提交
  const handleSubmit = async (values: any) => {
    // 检查是否有商品图片
    if (!attachments || attachments.length === 0) {
      message.error('请至少上传一张商品图片');
      return;
    }
    
    setLoading(true);
    try {
      if (isEdit && productId) {
        // 更新商品
        const updateData = {
          product_name: values.product_name,
          product_code: values.product_code,
          category_id: values.category_id,
          stock_quantity: values.stock_quantity,
          product_tags: tags.join(','), // 将标签数组转换为逗号分隔的字符串
          sales_type: values.sales_type,
          product_price: values.product_price * 100, // 转换为分
          cost_price: values.cost_price * 100,
          support_life_points: values.support_life_points,
          description: values.description,
          proxy_commission_ratio: values.proxy_commission_ratio / 100, // 百分比转小数
          sales_price: values.sales_price * 100,
          attachments: JSON.stringify(attachments), // 将attachments数组转换为JSON字符串
          skus: values.skus?.map((sku: any) => ({
            id: sku.id, // 保留原有SKU的ID
            sku_name: sku.sku_name,
            sku_price: sku.sku_price * 100, // 转换为分
            stock: sku.stock,
            strikethrough_price: sku.strikethrough_price ? sku.strikethrough_price * 100 : 0,
            spec_type: sku.spec_type,
            cost_price: sku.cost_price ? sku.cost_price * 100 : 0,
            stock_warning_threshold: sku.stock_warning_threshold,
            spec_json: sku.spec_json
          })) || []
        };

        console.log('更新商品数据:', updateData);
        const response = await updateProduct(productId, updateData);
        console.log('更新商品响应:', response);
      } else {
        // 创建商品
        const productData = {
          product_name: values.product_name,
          product_code: values.product_code,
          category_id: values.category_id,
          stock_quantity: values.stock_quantity,
          product_tags: tags.join(','), // 将标签数组转换为逗号分隔的字符串
          sales_type: values.sales_type,
          product_price: values.product_price * 100, // 转换为分
          cost_price: values.cost_price * 100,
          support_life_points: values.support_life_points,
          description: values.description,
          proxy_commission_ratio: values.proxy_commission_ratio / 100, // 百分比转小数
          sales_price: values.sales_price * 100,
          attachments: JSON.stringify(attachments), // 使用attachments数组
          skus: values.skus || []
        };

        console.log('创建商品数据:', productData);
        const response = await createProduct(productData);
        console.log('创建商品响应:', response);
        
        message.success('商品创建成功！');
      }
      
      onSuccess();
    } catch (error) {
      console.error('操作失败:', error);
      // 错误提示由全局请求拦截器处理
    } finally {
      setLoading(false);
    }
  };

  // OSS上传处理
  const handleUpload = async (file: File) => {
    try {
      console.log('开始获取OSS签名...');
      // 获取OSS签名
      const credentials = await getOssSign({ bucket: 'juezhi/publish' });
      console.log('OSS凭证:', credentials);
      
      if (!credentials) {
        throw new Error('OSS凭证数据为空');
      }

      // 生成文件名（参考Vue版本的格式）
      const timestamp = Date.now();
      const randomStr = Math.random().toString(36).substring(2, 15);
      const fileExtension = file.name.split('.').pop();
      const fileName = `image_${timestamp}_${randomStr}.${fileExtension}`;
      
      // 使用credentials.dir作为key前缀（参考Vue版本）
      const fileKey = `${credentials.dir}/${fileName}`;

      // 构建上传URL
      const uploadUrl = credentials.host;
      
      // 创建FormData（参考Vue版本的字段名）
      const formData = new FormData();
      formData.append('OSSAccessKeyId', credentials.ossAccessKeyId);
      formData.append('policy', credentials.policy);
      formData.append('Signature', credentials.signature); // 注意：使用Signature而不是signature
      formData.append('key', fileKey);
      formData.append('file', file);

      console.log('上传参数:', {
        key: fileKey,
        host: uploadUrl,
        fileName: fileName,
        originalName: file.name
      });

      // 上传到OSS
      const uploadResponse = await fetch(uploadUrl, {
        method: 'POST',
        body: formData
      });

      // 验证上传结果（阿里云OSS成功返回200或204）
      if (uploadResponse.status !== 200 && uploadResponse.status !== 204) {
        const errorText = await uploadResponse.text();
        console.error('上传失败响应:', errorText);
        throw new Error(`上传失败，状态码: ${uploadResponse.status}`);
      }

      // 构建文件URL（参考Vue版本使用credentials.dir）
      const fileUrl = `${credentials.host}/${credentials.dir}/${fileName}`;
      console.log('上传成功:', fileUrl);
      return fileUrl;
    } catch (error) {
      console.error('OSS上传失败:', error);
      message.error('文件上传失败');
      throw error;
    }
  };

  const uploadProps = {
    fileList,
    onChange: ({ fileList: newFileList }: any) => {
      // 只处理删除操作，不处理上传
      console.log('Upload onChange:', newFileList);
      setFileList(newFileList);
    },
    onRemove: (file: any) => {
      console.log('删除文件:', file);
      
      // 从fileList中删除
      setFileList(prev => prev.filter(item => item.uid !== file.uid));
      
      // 从attachments数组中删除对应的URL
      if (file.url) {
        setAttachments(prev => {
          const newList = prev.filter(att => att.url !== file.url);
          console.log('更新attachments数组(删除):', newList);
          return newList;
        });
      }
      
      return true;
    },
    beforeUpload: async (file: File) => {
      try {
        console.log('开始上传文件:', file.name);
        
        // 执行上传
        const fileUrl = await handleUpload(file);
        
        // 添加到attachments数组
        const newAttachment = { type: 'image', url: fileUrl };
        setAttachments(prev => {
          const newList = [...prev, newAttachment];
          console.log('更新attachments数组:', newList);
          return newList;
        });
        
        message.success(`${file.name} 上传成功`);
        return false; // 阻止默认上传
      } catch (error) {
        console.error('上传失败:', error);
        message.error(`${file.name} 上传失败`);
        return false;
      }
    },
    multiple: true,
    accept: 'image/*',
    showUploadList: {
      showPreviewIcon: true,
      showRemoveIcon: true,
      showDownloadIcon: false,
    },
    onPreview: (file: any) => {
      // 创建预览窗口
      const image = new Image();
      image.src = file.url || file.thumbUrl;
      
      // 创建预览容器
      const previewContainer = document.createElement('div');
      previewContainer.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
        cursor: pointer;
      `;
      
      // 创建图片元素
      const previewImage = document.createElement('img');
      previewImage.src = file.url || file.thumbUrl;
      previewImage.style.cssText = `
        max-width: 90%;
        max-height: 90%;
        object-fit: contain;
      `;
      
      previewContainer.appendChild(previewImage);
      document.body.appendChild(previewContainer);
      
      // 点击关闭预览
      previewContainer.onclick = () => {
        document.body.removeChild(previewContainer);
      };
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
    >
      {/* 基本信息 - 一行3个 */}
      <Row gutter={16}>
        <Col span={8}>
          <Form.Item
            label="商品名称"
            name="product_name"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            label="商品编码"
            name="product_code"
            rules={[{ required: true, message: '请输入商品编码' }]}
          >
            <Input placeholder="请输入商品编码" />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            label="商品分类"
            name="category_id"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select placeholder="请选择商品分类">
              <Option value={1}>健康科技</Option>
              <Option value={2}>生活用品</Option>
              <Option value={3}>食品饮料</Option>
              <Option value={4}>服装配饰</Option>
              <Option value={5}>数码电子</Option>
              <Option value={6}>家居用品</Option>
              <Option value={7}>运动户外</Option>
              <Option value={8}>美妆护肤</Option>
              <Option value={9}>其他</Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={8}>
          <Form.Item
            label="库存数量"
            name="stock_quantity"
            rules={[{ required: true, message: '请输入库存数量' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入库存数量" />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            label="销售类型"
            name="sales_type"
            rules={[{ required: true, message: '请选择销售类型' }]}
          >
            <Select placeholder="请选择销售类型">
              <Option value={1}>直销</Option>
              <Option value={2}>代理</Option>
              <Option value={3}>虚拟商品</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            label="商品价格（元）"
            name="product_price"
            rules={[{ required: true, message: '请输入商品价格' }]}
          >
            <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="请输入商品价格" />
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={8}>
          <Form.Item
            label="成本价格（元）"
            name="cost_price"
            rules={[{ required: true, message: '请输入成本价格' }]}
          >
            <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="请输入成本价格" />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            label="支持生命积分"
            name="support_life_points"
          >
            <Select placeholder="是否支持生命积分">
              <Option value={1}>支持</Option>
              <Option value={0}>不支持</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            label="代理佣金比例"
            name="proxy_commission_ratio"
            rules={[{ required: true, message: '请输入代理佣金比例' }]}
          >
            <InputNumber 
              min={0} 
              max={100} 
              step={1} 
              style={{ width: '100%' }} 
              placeholder="请输入代理佣金比例"
              addonAfter="%"
            />
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={8}>
          <Form.Item
            label="销售价格（元）"
            name="sales_price"
            rules={[{ required: true, message: '请输入销售价格' }]}
          >
            <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="请输入销售价格" />
          </Form.Item>
        </Col>
        <Col span={8}>
          {/* 空位，保持布局平衡 */}
        </Col>
        <Col span={8}>
          {/* 空位，保持布局平衡 */}
        </Col>
      </Row>

       <Row gutter={16}>
         <Col span={8}>
           <Form.Item
             label="商品标签"
             name="product_tags"
           >
             <div>
               {tags.map((tag) => (
                 <Tag
                   key={tag}
                   closable
                   onClose={() => handleClose(tag)}
                   style={{ marginBottom: '8px' }}
                 >
                   {tag}
                 </Tag>
               ))}
               {inputVisible ? (
                 <Input
                   type="text"
                   size="small"
                   style={{ width: 78 }}
                   value={inputValue}
                   onChange={handleInputChange}
                   onBlur={handleInputConfirm}
                   onPressEnter={handleInputConfirm}
                   autoFocus
                 />
               ) : (
                 <Tag onClick={showInput} style={{ borderStyle: 'dashed' }}>
                   <PlusOutlined /> 添加标签
                 </Tag>
               )}
             </div>
           </Form.Item>
         </Col>
         <Col span={16}>
           {/* 空位，保持布局平衡 */}
         </Col>
       </Row>

      {/* 商品描述 */}
      <Form.Item
        label="商品描述"
        name="description"
      >
        <TextArea rows={4} placeholder="请输入商品描述" />
      </Form.Item>

      <Divider>SKU规格</Divider>

      {/* SKU列表 - Table形式 */}
      <Form.List name="skus">
        {(fields, { add, remove }) => {
          const columns = [
            {
              title: 'SKU名称',
              dataIndex: 'sku_name',
              key: 'sku_name',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'sku_name']}
                  rules={[{ required: true, message: '请输入SKU名称' }]}
                  style={{ margin: 0 }}
                >
                  <Input placeholder="如：红色-M" />
                </Form.Item>
              ),
            },
            {
              title: 'SKU价格（元）',
              dataIndex: 'sku_price',
              key: 'sku_price',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'sku_price']}
                  rules={[{ required: true, message: '请输入SKU价格' }]}
                  style={{ margin: 0 }}
                >
                  <InputNumber min={0} step={0.01} style={{ width: '100%' }} />
                </Form.Item>
              ),
            },
            {
              title: '库存',
              dataIndex: 'stock',
              key: 'stock',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'stock']}
                  rules={[{ required: true, message: '请输入库存' }]}
                  style={{ margin: 0 }}
                >
                  <InputNumber min={0} style={{ width: '100%' }} />
                </Form.Item>
              ),
            },
            {
              title: '划线价格（元）',
              dataIndex: 'strikethrough_price',
              key: 'strikethrough_price',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'strikethrough_price']}
                  style={{ margin: 0 }}
                >
                  <InputNumber min={0} step={0.01} style={{ width: '100%' }} />
                </Form.Item>
              ),
            },
            {
              title: '规格类型',
              dataIndex: 'spec_type',
              key: 'spec_type',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'spec_type']}
                  style={{ margin: 0 }}
                >
                  <Input placeholder="如：颜色尺码" />
                </Form.Item>
              ),
            },
            {
              title: '成本价格（元）',
              dataIndex: 'cost_price',
              key: 'cost_price',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'cost_price']}
                  style={{ margin: 0 }}
                >
                  <InputNumber min={0} step={0.01} style={{ width: '100%' }} />
                </Form.Item>
              ),
            },
            {
              title: '库存预警阈值',
              dataIndex: 'stock_warning_threshold',
              key: 'stock_warning_threshold',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'stock_warning_threshold']}
                  style={{ margin: 0 }}
                >
                  <InputNumber min={0} style={{ width: '100%' }} />
                </Form.Item>
              ),
            },
            {
              title: '规格JSON',
              dataIndex: 'spec_json',
              key: 'spec_json',
              render: (_: any, __: any, index: number) => (
                <Form.Item
                  name={[index, 'spec_json']}
                  style={{ margin: 0 }}
                >
                  <Input placeholder='{"颜色":"红色","尺码":"M"}' />
                </Form.Item>
              ),
            },
            {
              title: '操作',
              key: 'action',
              render: (_: any, __: any, index: number) => (
                <Popconfirm
                  title="确定要删除这个SKU吗？"
                  onConfirm={() => remove(index)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="link" danger>
                    删除
                  </Button>
                </Popconfirm>
              ),
            },
          ];

          return (
            <>
              <Table
                columns={columns}
                dataSource={fields}
                pagination={false}
                rowKey={(_, index) => `sku-${index}`}
                size="small"
                bordered
              />
              <Form.Item style={{ marginTop: 16 }}>
                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                  添加SKU规格
                </Button>
              </Form.Item>
            </>
          );
        }}
      </Form.List>

      {/* 商品图片 */}
      <Form.Item
        label="商品图片"
        name="attachments"
      >
        <div>
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />}>上传图片</Button>
          </Upload>
        
        {/* 图片预览区域 - 使用attachments数组 */}
        {attachments.length > 0 && (
          <div style={{ marginTop: '16px' }}>
            <div style={{ marginBottom: '8px', color: '#666', fontSize: '12px' }}>
              已上传 {attachments.length} 张图片
            </div>
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(3, 1fr)',
              gap: '12px'
            }}>
              {attachments.map((attachment, index) => {
                console.log('渲染图片:', attachment);
                return (
                <div
                  key={`attachment-${index}`}
                  style={{
                    position: 'relative',
                    aspectRatio: '1',
                    borderRadius: '12px',
                    overflow: 'hidden',
                    border: '1px solid #e5e7eb'
                  }}
                >
                  <img
                    src={attachment.url}
                    alt={`图片${index + 1}`}
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover'
                    }}
                    onError={(e) => {
                      console.error('图片加载失败:', attachment);
                      console.error('图片URL:', attachment.url);
                      e.currentTarget.style.display = 'none';
                    }}
                    onLoad={() => {
                      console.log('图片加载成功:', attachment.url);
                    }}
                  />
                  <div
                    style={{
                      position: 'absolute',
                      top: '0',
                      left: '0',
                      right: '0',
                      bottom: '0',
                      background: 'rgba(0, 0, 0, 0.3)',
                      opacity: '0',
                      transition: 'opacity 0.2s ease',
                      display: 'flex',
                      alignItems: 'flex-start',
                      justifyContent: 'flex-end',
                      padding: '8px',
                      cursor: 'pointer'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.opacity = '1';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.opacity = '0';
                    }}
                    onClick={() => {
                      // 预览图片
                      const previewContainer = document.createElement('div');
                      previewContainer.style.cssText = `
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(0, 0, 0, 0.8);
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        z-index: 9999;
                        cursor: pointer;
                      `;
                      
                      const previewImage = document.createElement('img');
                      previewImage.src = attachment.url;
                      previewImage.style.cssText = `
                        max-width: 90%;
                        max-height: 90%;
                        object-fit: contain;
                      `;
                      
                      previewContainer.appendChild(previewImage);
                      document.body.appendChild(previewContainer);
                      
                      previewContainer.onclick = () => {
                        document.body.removeChild(previewContainer);
                      };
                    }}
                  >
                    <div
                      style={{
                        width: '32px',
                        height: '32px',
                        borderRadius: '50%',
                        background: 'rgba(239, 68, 68, 0.8)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        cursor: 'pointer',
                        transition: 'background 0.2s ease'
                      }}
                      onClick={(e) => {
                        e.stopPropagation();
                        // 删除图片 - 从attachments数组中删除
                        setAttachments(prev => {
                          const newList = prev.filter((_, i) => i !== index);
                          console.log('删除图片后的attachments:', newList);
                          return newList;
                        });
                      }}
                    >
                      <span style={{ 
                        color: 'white', 
                        fontSize: '16px',
                        lineHeight: '1',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}>×</span>
                    </div>
                  </div>
                </div>
                );
              })}
            </div>
          </div>
        )}
        </div>
      </Form.Item>

      {/* 提交按钮 - 居右 */}
      <Form.Item style={{ textAlign: 'right' }}>
        <Space>
          <Button onClick={onCancel}>
            取消
          </Button>
          <Button type="primary" htmlType="submit" loading={loading}>
            {isEdit ? '更新商品' : '创建商品'}
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default CommodityEditForm;
